package cn.edw.swu.bc.todolist

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    lateinit var dbUserHelper: DBUserHelper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dbUserHelper = DBUserHelper(this, "user.db", 1)
        initView()
    }

    fun initView() {

        val btn_login = findViewById<Button>(R.id.btn_login)
        val btn_register = findViewById<Button>(R.id.btn_register)
        val intent = Intent(this, cn.edw.swu.bc.todolist.ListActivity::class.java)
        // 为登录按钮绑定click事件
        btn_login.setOnClickListener {
            val username = findViewById<EditText>(R.id.ipt_username).text.toString()
            val password = findViewById<EditText>(R.id.ipt_password).text.toString()
            if (username.isEmpty() || password.isEmpty())
                Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show()
            else {
                val login_code = dbUserHelper.login(username, password)
                if (login_code == DBUserHelper.LOGIN_SUCCESSFUL) {
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
                    startActivity(intent)
                } else
                    Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show()
            }
        }

        // 为注册按钮绑定click事件
        btn_register.setOnClickListener {
            val username = findViewById<EditText>(R.id.ipt_username).text.toString()
            val password = findViewById<EditText>(R.id.ipt_password).text.toString()
            if (username.isEmpty() || password.isEmpty())
                Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show()
            else {
                val id = dbUserHelper.register(username, password)
                if (id >= 0) {
                    Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show()

                    startActivity(intent)
                } else
                    Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show()
            }
        }
        //

    }
}